
var WUI={

    base: "",
    locale: "zh_CN",
    loginUrl:"",
    keyCode: {
        ENTER: 13, ESC: 27, END: 35, HOME: 36,
        SHIFT: 16, TAB: 9,
        LEFT: 37, RIGHT: 39, UP: 38, DOWN: 40,
        DELETE: 46, BACKSPACE:8
    },
    isOverAxis: function(x, reference, size) {
        //Determines when x coordinate is over "b" element axis
        return (x > reference) && (x < (reference + size));
    },
    isOver: function(y, x, top, left, height, width) {
        //Determines when x, y coordinates is over "b" element
        return this.isOverAxis(y, top, height) && this.isOverAxis(x, left, width);
    },
    pageInfo: {pageNum:"pageNum", numPerPage:"numPerPage", orderField:"orderField", orderDirection:"orderDirection"},
    statusCode: {ok:200, error:300, timeout:301},
    keys: {statusCode:"statusCode", message:"message"},
    frag:{}, //page fragment
    _msg:{}, //alert message
    _set:{
        loginUrl:"", //session timeout
        loginTitle:"", //if loginTitle open a login dialog
        debug:false
    },
    ajaxError:function(xhr, ajaxOptions, thrownError){
        //layer.alert("Http status: " + xhr.status + " " + xhr.statusText + "\najaxOptions: " + ajaxOptions + "\nthrownError:"+thrownError + "\n" +xhr.responseText);
        if(xhr.status==404){
            layer.alert("对不起,提交的地址不存在");
        }
        else{
            layer.alert("服务器错误");
        }
    },
    ajaxDone:function(json){
        if(json[WUI.keys.statusCode] == WUI.statusCode.error) {
            layer.alert(json[WUI.keys.message]);
        } else if (json[WUI.keys.statusCode] == WUI.statusCode.timeout) {
            WUI.loadLogin();
        } else if (json[WUI.keys.statusCode] == WUI.statusCode.ok){
            layer.alert(json[WUI.keys.message]);
        };
    },
    loadLogin:function(){

    }
};


var setting = {
    priceScale: "2",
    priceRoundType: "roundHalfUp",
    currencySign: "￥",
    currencyUnit: "元",
    uploadImageExtension: "jpg,jpeg,bmp,gif,png",
    uploadFlashExtension: "swf,flv",
    uploadMediaExtension: "swf,flv,mp3,wav,avi,rm,rmvb",
    uploadFileExtension: "zip,rar,7z,doc,docx,xls,xlsx,ppt,pptx,csv"
};

var messages = {
    "site.message.success": "操作成功",
    "site.message.error": "操作错误",
    "site.dialog.ok": "确&nbsp;&nbsp;定",
    "site.dialog.cancel": "取&nbsp;&nbsp;消",
    "site.dialog.deleteConfirm": "您确定要删除吗？",
    "site.dialog.clearConfirm": "您确定要清空吗？",
    "site.validate.required": "必填",
    "site.validate.email": "E-mail格式错误",
    "site.validate.url": "网址格式错误",
    "site.validate.date": "日期格式错误",
    "site.validate.dateISO": "日期格式错误",
    "site.validate.pointcard": "信用卡格式错误",
    "site.validate.number": "只允许输入数字",
    "site.validate.digits": "只允许输入零或正整数",
    "site.validate.minlength": "长度不允许小于{0}",
    "site.validate.maxlength": "长度不允许大于{0}",
    "site.validate.rangelength": "长度必须在{0}-{1}之间",
    "site.validate.min": "不允许小于{0}",
    "site.validate.max": "不允许大于{0}",
    "site.validate.range": "必须在{0}-{1}之间",
    "site.validate.accept": "输入后缀错误",
    "site.validate.equalTo": "两次输入不一致",
    "site.validate.remote": "输入错误",
    "site.validate.integer": "只允许输入整数",
    "site.validate.positive": "只允许输入正数",
    "site.validate.negative": "只允许输入负数",
    "site.validate.decimal": "数值超出了允许范围",
    "site.validate.pattern": "格式错误",
    "site.validate.extension": "文件格式错误"
};

// 添加Cookie
function addCookie(name, value, options) {
    if (arguments.length > 1 && name != null) {
        if (options == null) {
            options = {};
        }
        if (value == null) {
            options.expires = -1;
        }
        if (typeof options.expires == "number") {
            var time = options.expires;
            var expires = options.expires = new Date();
            expires.setTime(expires.getTime() + time * 1000);
        }
        document.cookie = encodeURIComponent(String(name)) + "=" + encodeURIComponent(String(value)) + (options.expires ? "; expires=" + options.expires.toUTCString() : "") + (options.path ? "; path=" + options.path : "") + (options.domain ? "; domain=" + options.domain : ""), (options.secure ? "; secure" : "");
    }
}

// 获取Cookie
function getCookie(name) {
    if (name != null) {
        var value = new RegExp("(?:^|; )" + encodeURIComponent(String(name)) + "=([^;]*)").exec(document.cookie);
        return value ? decodeURIComponent(value[1]) : null;
    }
}

// 移除Cookie
function removeCookie(name, options) {
    addCookie(name, null, options);
}

// 货币格式化
function currency(value, showSign, showUnit) {
    if (value != null) {
        var price;
        if (setting.priceRoundType == "roundHalfUp") {
            price = (Math.round(value * Math.pow(10, setting.priceScale)) / Math.pow(10, setting.priceScale)).toFixed(setting.priceScale);
        } else if (setting.priceRoundType == "roundUp") {
            price = (Math.ceil(value * Math.pow(10, setting.priceScale)) / Math.pow(10, setting.priceScale)).toFixed(setting.priceScale);
        } else {
            price = (Math.floor(value * Math.pow(10, setting.priceScale)) / Math.pow(10, setting.priceScale)).toFixed(setting.priceScale);
        }
        if (showSign) {
            price = setting.currencySign + price;
        }
        if (showUnit) {
            price += setting.currencyUnit;
        }
        return price;
    }
}


/**
 * 普通ajax表单提交
 * @param {Object} form
 * @param {Object} callback
 * @param {String} confirmMsg 提示确认信息
 */
function validateForm(form) {
    var $form = $(form);
    if (!$form.valid()) {
        return false;
    }
}


// 多语言
function message(code) {
    if (code != null) {
        var content = messages[code] != null ? messages[code] : code;
        if (arguments.length == 1) {
            return content;
        } else {
            if ($.isArray(arguments[1])) {
                $.each(arguments[1], function(i, n) {
                    content = content.replace(new RegExp("\\{" + i + "\\}", "g"), n);
                });
                return content;
            } else {
                $.each(Array.prototype.slice.apply(arguments).slice(1), function(i, n) {
                    content = content.replace(new RegExp("\\{" + i + "\\}", "g"), n);
                });
                return content;
            }
        }
    }
}

/**
 * 普通ajax表单提交
 * @param {Object} form
 * @param {Object} callback
 * @param {String} confirmMsg 提示确认信息
 */
function validateCallback(form, callback, confirmMsg) {
    var $form = $(form);
    if (!$form.valid()) {
        return false;
    }
    var _submitFn = function(){
        $.ajax({
            type: form.method || 'POST',
            url:$form.attr("action"),
            data:$form.serializeArray(),
            dataType:"json",
            cache: false,
            success: callback || WUI.ajaxDone,
            error: WUI.ajaxError
        });
    };
    //询问
    if (confirmMsg) {
        $.layer({
            shade: [0],
            area: ['auto','auto'],
            dialog: {
                msg: confirmMsg,
                btns: 2,
                type: 4,
                btn: ['确认','取消'],
                yes: function(){
                    _submitFn();
                },
                no: function(){
                    return false;
                }
            }
        });
    } else {
        _submitFn();
    }
    return false;
}




/*** Public Jquery Plug**/

(function($) {

    var zIndex = 100;

    // 检测登录
    $.checkLogin = function() {
        var result = false;
        $.ajax({
            url: WUI.loginUrl,
            type: "GET",
            dataType: "json",
            cache: false,
            async: false,
            success: function(data) {
                result = data;
            }
        });
        return result;
    };

    // 跳转登录
    $.redirectLogin = function (redirectUrl, message) {
        var href = WUI.loginUrl;
        if (redirectUrl != null) {
            href += "?redirectUrl=" + encodeURIComponent(redirectUrl);
        }
        if (message != null) {
            $.message("warn", message);
            setTimeout(function() {
                location.href = href;
            }, 1000);
        } else {
            location.href = href;
        }
    };

    // 消息框
    var $message;
    var messageTimer;
    $.message = function() {
        var message = {};
        if ($.isPlainObject(arguments[0])) {
            message = arguments[0];
        } else if (typeof arguments[0] === "string" && typeof arguments[1] === "string") {
            message.type = arguments[0];
            message.content = arguments[1];
        } else {
            return false;
        }

        if (message.type == null || message.content == null) {
            return false;
        }

        if ($message == null) {
            $message = $('<div class="xxMessage"><div class="messageContent message' + message.type + 'Icon"><\/div><\/div>');
            if (!window.XMLHttpRequest) {
                $message.append('<iframe class="messageIframe"><\/iframe>');
            }
            $message.appendTo("body");
        }

        $message.children("div").removeClass("messagewarnIcon messageerrorIcon messagesuccessIcon").addClass("message" + message.type + "Icon").html(message.content);
        $message.css({"margin-left": - parseInt($message.outerWidth() / 2), "z-index": zIndex ++}).show();

        clearTimeout(messageTimer);
        messageTimer = setTimeout(function() {
            $message.hide();
        }, 3000);
        return $message;
    };

    // 令牌	
    $(document).ajaxSend(function(event, request, settings) {
        if (!settings.crossDomain && settings.type != null && settings.type.toLowerCase() == "post") {
            var token = getCookie("token");
            if (token != null) {
                request.setRequestHeader("token", token);
            }
        }
    });

    $(document).ajaxComplete(function(event, request, settings) {
        var loginStatus = request.getResponseHeader("loginStatus");
        var tokenStatus = request.getResponseHeader("tokenStatus");

        if (loginStatus == "accessDenied") {
            $.redirectLogin(location.href, "请登录后再进行操作");
        } else if (tokenStatus == "accessDenied") {
            var token = getCookie("token");
            if (token != null) {
                $.extend(settings, {
                    global: false,
                    headers: {token: token}
                });
                $.ajax(settings);
            }
        }
    });

    //Dialog
    var $p = $(document);
    // dialog
    $("a[target=dialog]", $p).each(function(){
        $(this).click(function(event){
            var $this = $(this);
            var title = $this.attr("title") || $this.text();
            var url =$this.attr("href") || "/";
            var width=$this.attr("width")||1000;
            var height=$this.attr("height")||($(window).height() - 50);
            $.layer({
                type: 2,
                maxmin: true,
                shadeClose: true,
                title: title,
                shade: [0.1,'#fff'],
                offset: ['20px',''],
                area: [width+"px", height +'px'],
                iframe: {src: url}
            });
            return false;
        });
    });


    //Ajax
    $.fn.extend({
        /**
         * @param {Object} op: {type:GET/POST, url:ajax请求地址, data:ajax请求参数列表, callback:回调函数 }
         */
        ajaxUrl: function(op){
            var $this = $(this);
            $this.trigger(WUI.eventType.pageClear);
            $.ajax({
                type: op.type || 'GET',
                url: op.url,
                data: op.data,
                cache: false,
                success: function(response){
                    var json = WUI.jsonEval(response);
                    if (json[WUI.keys.statusCode]==WUI.statusCode.error){
                        if (json[WUI.keys.message]) layer.alert(json[WUI.keys.message]);
                    } else {
                        if ($.isFunction(op.callback)) op.callback(response);
                    }
                    if (json[WUI.keys.statusCode]==WUI.statusCode.timeout){
                        //需要登录
                    }
                },
                error: WUI.ajaxError,
                statusCode: {
                    503: function(xhr, ajaxOptions, thrownError) {
                        alert(WUI.msg("statusCode_503") || thrownError);
                    }
                }
            });
        },
        loadUrl: function(url,data,callback){
            $(this).ajaxUrl({url:url, data:data, callback:callback});
        }
    });



})(jQuery);

// 令牌
$().ready(function() {

    $("form").submit(function() {
        var $this = $(this);
        if ($this.attr("method") != null && $this.attr("method").toLowerCase() == "post" && $this.find("input[name='token']").size() == 0) {
            var token = getCookie("token");
            if (token != null) {
                $this.append('<input type="hidden" name="token" value="' + token + '" \/>');
            }
        }
    });

    var $listForm = $("#listForm");
    var $pageNumber = $("#pageNumber");
    // 表单提交
    $listForm.submit(function() {
        if (!/^\d*[1-9]\d*$/.test($pageNumber.val())) {
            $pageNumber.val("1");
        }
    });
    // 页码跳转
    $.pageSkip = function(pageNumber) {
        $pageNumber.val(pageNumber);
        $listForm.submit();
        return false;
    };

    $("#getCode").click(function(){
         var phone=$("#username").val();
         var dataType=$(this).attr("data-type");
         if($(this).hasClass("disabled")){
             return false;
         }
         if(isMobile(phone)==4){
             layer.open({
                 content: "请输入正确的手机号码",
                 time: 2
             });
             return false;
         }
        setSMSBtnTime();
         layer.open({
            type: 2,
            content: '获取验证码~'
        });
         $.ajax({
            url: "/get_sms_code",
            type: "GET",
            data: {
                phone: phone,
                type : dataType
            },
            dataType: "json",
            cache: false,
            success: function(message) {
               $("#user-reg").removeClass("disabled");
                layer.closeAll();
                layer.open({
                    content: message.content,
                    time: 2
                });
            },error:function(){
                $("#user-reg").removeClass("disabled");
                layer.closeAll();
                layer.open({
                    content: "服务器异常",
                    time: 2
                });
            }
        });
        return false;
    });

    function isMobile(m){
        var p1 = /^((134|135|136|137|138|139|150|151|152|157|158|159|182|183|184|187|178|188|147))\d{8}$/;  //移动
        var p2 = /^((130|131|132|145|155|156|176|185|186))\d{8}$/;
        var p3=/^((133|153|180|181|189|177))\d{8}$/;
        if(p1.test(m)){ return 1; }
        else if(p2.test(m)){return 2;}
        else if(p3.test(m)){return 3;}
        else{return 4;}
    }

    if ($.tools != null) {
        var $tab = $(".tab-header");
        var $title = $("#inputForm :input[title], #inputForm label[title]");

        // Tab效果
        $tab.tabs("div.tabContent .tab-page", {
            tabs: "tab-page"
        });

        // 表单提示
        $title.tooltip({
            position: "center right",
            offset: [0, 4],
            effect: "fade"
        });
    }

});

var s = 60;
function setSMSBtnTime(){
    s--;
    $("#getCode").addClass("disabled");
    $("#getCode").val(""+s+"秒");
    t=setTimeout(function(){setSMSBtnTime()}, 1000);
    if ( s <= 0 ){
        s = 60;
        $("#getCode").val("获取验证码");
        $("#getCode").removeClass("disabled");
        clearTimeout(t);
    }
}

// 验证消息
if ($.validator != null) {
    $.extend($.validator.messages, {
        required: message("site.validate.required"),
        email: message("site.validate.email"),
        url: message("site.validate.url"),
        date: message("site.validate.date"),
        dateISO: message("site.validate.dateISO"),
        pointcard: message("site.validate.pointcard"),
        number: message("site.validate.number"),
        digits: message("site.validate.digits"),
        minlength: $.validator.format(message("site.validate.minlength")),
        maxlength: $.validator.format(message("site.validate.maxlength")),
        rangelength: $.validator.format(message("site.validate.rangelength")),
        min: $.validator.format(message("site.validate.min")),
        max: $.validator.format(message("site.validate.max")),
        range: $.validator.format(message("site.validate.range")),
        accept: message("site.validate.accept"),
        equalTo: message("site.validate.equalTo"),
        remote: message("site.validate.remote"),
        integer: message("site.validate.integer"),
        positive: message("site.validate.positive"),
        negative: message("site.validate.negative"),
        decimal: message("site.validate.decimal"),
        pattern: message("site.validate.pattern"),
        extension: message("site.validate.extension")
    });

    $.validator.setDefaults({
        errorClass: "fieldError",
        ignore: ".ignore",
        ignoreTitle: true,
        errorPlacement: function(error, element) {
            var fieldSet = element.closest("span.fieldSet");
            if (fieldSet.size() > 0) {
                error.appendTo(fieldSet);
            } else {
                error.insertAfter(element);
            }
        },
        submitHandler: function(form) {
            $(form).find(":submit").prop("disabled", true);
            form.submit();
        }
    });
}